from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                             QLineEdit, QPushButton, QMessageBox, QCheckBox)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QIcon, QPixmap
from db.db_util import DBUtil
import re

class RegisterDialog(QDialog):
    """用户注册窗口"""
    register_success = pyqtSignal()  # 注册成功信号（通知登录窗口刷新）

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("点云处理系统 - 注册")
        self.setFixedSize(450, 400)
        self.setWindowFlags(Qt.Window | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint)
        self.init_ui()

    def init_ui(self):
        """初始化注册界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(30, 30, 30, 30)
        main_layout.setSpacing(15)

        # 图标
        icon_label = QLabel()
        icon_label.setAlignment(Qt.AlignCenter)
        icon = QIcon.fromTheme("user-add", QIcon("point_cloud_icon.png"))
        pixmap = icon.pixmap(80, 80)
        icon_label.setPixmap(pixmap)
        main_layout.addWidget(icon_label)

        # 用户名输入
        username_layout = QHBoxLayout()
        username_label = QLabel("用户名：")
        username_label.setStyleSheet("color: white; font-size: 14px;")
        self.username_edit = QLineEdit()
        self.username_edit.setPlaceholderText("请输入3-20位字母/数字/下划线")
        self.username_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px; border: 1px solid #666; border-radius: 5px;
                background-color: #333; color: white;
            }
            QLineEdit:focus { border-color: #2196F3; outline: none; }
        """)
        username_layout.addWidget(username_label)
        username_layout.addWidget(self.username_edit)
        main_layout.addLayout(username_layout)

        # 密码输入
        password_layout = QHBoxLayout()
        password_label = QLabel("密  码：")
        password_label.setStyleSheet("color: white; font-size: 14px;")
        self.password_edit = QLineEdit()
        self.password_edit.setPlaceholderText("请输入6-20位密码（含字母和数字）")
        self.password_edit.setEchoMode(QLineEdit.Password)
        self.password_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px; border: 1px solid #666; border-radius: 5px;
                background-color: #333; color: white;
            }
            QLineEdit:focus { border-color: #2196F3; outline: none; }
        """)
        password_layout.addWidget(password_label)
        password_layout.addWidget(self.password_edit)
        main_layout.addLayout(password_layout)

        # 确认密码输入
        confirm_pwd_layout = QHBoxLayout()
        confirm_pwd_label = QLabel("确认密码：")
        confirm_pwd_label.setStyleSheet("color: white; font-size: 14px;")
        self.confirm_pwd_edit = QLineEdit()
        self.confirm_pwd_edit.setPlaceholderText("请再次输入密码")
        self.confirm_pwd_edit.setEchoMode(QLineEdit.Password)
        self.confirm_pwd_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px; border: 1px solid #666; border-radius: 5px;
                background-color: #333; color: white;
            }
            QLineEdit:focus { border-color: #2196F3; outline: none; }
        """)
        confirm_pwd_layout.addWidget(confirm_pwd_label)
        confirm_pwd_layout.addWidget(self.confirm_pwd_edit)
        main_layout.addLayout(confirm_pwd_layout)

        # 邮箱输入
        email_layout = QHBoxLayout()
        email_label = QLabel("邮  箱：")
        email_label.setStyleSheet("color: white; font-size: 14px;")
        self.email_edit = QLineEdit()
        self.email_edit.setPlaceholderText("请输入有效邮箱（用于密码找回）")
        self.email_edit.setStyleSheet("""
            QLineEdit {
                padding: 8px; border: 1px solid #666; border-radius: 5px;
                background-color: #333; color: white;
            }
            QLineEdit:focus { border-color: #2196F3; outline: none; }
        """)
        email_layout.addWidget(email_label)
        email_layout.addWidget(self.email_edit)
        main_layout.addLayout(email_layout)

        # 同意协议（复选框）
        agree_layout = QHBoxLayout()
        self.agree_checkbox = QCheckBox("我已阅读并同意用户协议")
        self.agree_checkbox.setStyleSheet("""
            QCheckBox { color: white; font-size: 12px; }
            QCheckBox::indicator { width: 16px; height: 16px; }
        """)
        agree_layout.addStretch()
        agree_layout.addWidget(self.agree_checkbox)
        main_layout.addLayout(agree_layout)

        # 注册按钮
        register_btn = QPushButton("注册")
        register_btn.setStyleSheet("""
            QPushButton {
                background-color: #2196F3; color: white; font-size: 16px;
                font-weight: bold; padding: 10px; border-radius: 5px; border: none;
            }
            QPushButton:hover { background-color: #1976D2; }
            QPushButton:pressed { background-color: #1565C0; }
            QPushButton:disabled { background-color: #555; }
        """)
        register_btn.clicked.connect(self.handle_register)
        main_layout.addWidget(register_btn, alignment=Qt.AlignCenter)

        # 窗口背景
        self.setStyleSheet("background-color: #2b2b2b;")

    def validate_input(self):
        """验证输入合法性（简化密码校验）"""
        username = self.username_edit.text().strip()
        password = self.password_edit.text().strip()
        confirm_pwd = self.confirm_pwd_edit.text().strip()
        email = self.email_edit.text().strip()

        # 1. 非空校验
        if not username or not password or not confirm_pwd or not email:
            QMessageBox.warning(self, "警告", "所有字段不能为空！")
            return False

        # 2. 用户名校验（3-20位字母/数字/下划线，不变）
        if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username):
            QMessageBox.warning(self, "警告", "用户名格式错误！需为3-20位字母/数字/下划线")
            return False

        # 3. 简化密码校验（仅限制长度6-20位，不限制字符类型）
        if len(password) < 6 or len(password) > 20:
            QMessageBox.warning(self, "警告", "密码格式错误！需为6-20位")
            return False

        # 4. 确认密码校验（不变）
        if password != confirm_pwd:
            QMessageBox.warning(self, "警告", "两次输入的密码不一致！")
            return False

        # 5. 邮箱校验（不变）
        if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
            QMessageBox.warning(self, "警告", "邮箱格式错误！请输入有效邮箱")
            return False

        # 6. 同意协议校验（不变）
        if not self.agree_checkbox.isChecked():
            QMessageBox.warning(self, "警告", "请阅读并同意用户协议！")
            return False

        return True

    def handle_register(self):
        """处理注册逻辑"""
        if not self.validate_input():
            return

        # 获取输入信息
        username = self.username_edit.text().strip()
        password = self.password_edit.text().strip()
        email = self.email_edit.text().strip()

        # 加密密码
        password_hash = DBUtil.hash_password(password)

        # 调用数据库工具类注册用户
        if DBUtil.register_user(username, password_hash, email):
            QMessageBox.information(self, "成功", "注册成功！请返回登录界面登录")
            self.register_success.emit()  # 发送注册成功信号
            self.close()
        else:
            QMessageBox.critical(self, "失败", "注册失败！用户名或邮箱已被占用")